package com.example.springboot.redis.demo.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@RestController
@RequestMapping(value = "/redis")
public class TestController {

    private static final Logger log = LoggerFactory.getLogger(TestController.class);

    @Autowired
    private RedisTemplate redisTemplate;

    @GetMapping(value = "/batchinsert/{num}")
    public void addKey(@PathVariable int num) {
        for (int i = 0; i < num; i++) {
            redisTemplate.opsForValue().set("key" + i, "value" + i);
        }
    }

    @GetMapping(value = "/batch/{num}")
    public void batchInsert(@PathVariable int num) {
        Map map = new ConcurrentHashMap(80000);
        for (int i = 0; i < num; i++) {
            map.put("key" + i, "value" + i);
        }
        log.info("batch insert start " + System.currentTimeMillis());
        redisTemplate.opsForValue().multiSet(map);
        log.info("batch insert end " + System.currentTimeMillis());
    }

    @GetMapping(value = "/get/{key}")
    public String getKey(@PathVariable(value = "key") String key) {
        return String.valueOf(redisTemplate.opsForValue().get(key));
    }

    @GetMapping(value = "/del/{key}")
    public boolean deleteKey(@PathVariable(value = "key") String key) {
        return redisTemplate.delete(key);
    }

}
